<?php
/**
 * @file : celebrityrelation.php
 * @date : 2015-01-04
 */
namespace haibao\cms\data;

use \haibao\frame\data\query\Condition;
use haibao\cms\model\filter\CelebrityRelation as CelebrityRelationFilter;
use haibao\cms\model\filter\RelationType as RelationTypeFilter;

class CelebrityRelation extends \haibao\cms\data\BaseMysql{

    public function __construct(){
        parent::__construct('\haibao\cms\model\data\CelebrityImage');
    }
    
    /**
     * 根据明星标签ID获取明星与明星关联关系
     * @param : Int $tagId
     *     
     */
    public function getCelebrityRelByTagId($tagId){
    	$tagData = new \haibao\cms\data\Tag();
    	$celebrityRels = '';
    	// TODO : 获取topicId
    	$topicArr = $tagData->getTopicIdByTagId(array($tagId));
    	$topicId = $topicArr[$tagId];
    	$celebrityRelFilter = new CelebrityRelationFilter();
    	$celebrityRelFilter->select(array(
    			CelebrityRelationFilter::CONDITION_FIELD_NAME_JOIN_CELEBRITY,	
    			CelebrityRelationFilter::CONDITION_FIELD_NAME_RELATION_TYPE_ID,	
    	));
    	
    	$relationTypeFilter = new RelationTypeFilter;
    	$relationTypeFilter->select(array(
    			RelationTypeFilter::CONDITION_FIELD_NAME_TYPE_NAME
    	));
    	$celebrityRelFilter->where(CelebrityRelationFilter::CONDITION_FIELD_NAME_MASTAR_CELEBRITY,Condition::CONDITION_EQUAL,$topicId);
    	$celebrityRelFilter->leftjoin($relationTypeFilter,null,CelebrityRelationFilter::CONDITION_FIELD_NAME_RELATION_TYPE_ID,RelationTypeFilter::CONDITION_FIELD_NAME_ID,CelebrityRelationFilter::CONDITION_FIELD_NAME_RELATION_TYPE_NAME,false);
    	
    	$celebrityRels = $this->getAll($celebrityRelFilter);
    	$joinCelebrityArr = array();
    	if($celebrityRels){
    		foreach($celebrityRels as $rel){
    			
    			$joinCelebrityArr[] = $rel->JoinCelebrity;
    		}
    		
    		$tagIds = $tagData->getTagIdByTopicId($joinCelebrityArr);
                		
    		$celebrityData = new \haibao\cms\data\Celebrity();
    		$celebrities = $celebrityData->getCelebrityByTagId($tagIds);
    	    foreach($celebrityRels as $rel){
    			
    	    	$rel->TagId = $tagIds[$rel->JoinCelebrity];
    	    	foreach($celebrities as $celebrity){
    	    		if($celebrity->TagId == $rel->TagId){
    	    			$rel->CelebrityName = $celebrity->NameCn;
    	    			break;
    	    		}
    	    	}
    		}
    		return $celebrityRels;
        }
    }
}
